package cn.com.gridinfo.sooc.core.course.classes.fragment;


import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.jeremy.arad.Arad;
import com.jeremy.arad.utils.Log;
import com.pili.pldroid.player.AVOptions;
import com.pili.pldroid.player.PLMediaPlayer;
import com.pili.pldroid.player.widget.PLVideoTextureView;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import cn.com.gridinfo.sooc.R;
import cn.com.gridinfo.sooc.base.BaseSoocFragment;
import cn.com.gridinfo.sooc.common.LocalMark;
import cn.com.gridinfo.sooc.core.course.classes.activity.CourseDetailActivity;
import cn.com.gridinfo.sooc.core.course.classes.bean.CourseDetailsInfo;
import cn.com.gridinfo.sooc.core.course.classes.dao.CourseDao;
import cn.com.gridinfo.sooc.core.course.classes.fragment.videocontrol.MediaController;
import cn.com.gridinfo.sooc.core.course.common.CodeConst;
import cn.com.gridinfo.sooc.core.course.directory.bean.MenuDisplay;
import cn.com.gridinfo.sooc.utils.MessageUtils;

/**
 * 视频 fragment
 *
 * @author jieli
 */
public class VideoFragment extends BaseSoocFragment {

    View view;

    //视频容器
    @InjectView(R.id.container)
    FrameLayout fcontainer;

    //视频播放器布局
    @InjectView(R.id.videoView)
    PLVideoTextureView mVideoView;

    //加载页面布局
    @InjectView(R.id.LoadingView)
    LinearLayout loadingView;

    //非 wifi布局界面
    @InjectView(R.id.video_noWifi)
    RelativeLayout videoNoWifiLayout;
    @InjectView(R.id.noNetWork_tv)
    TextView noNetWorkTv;
    @InjectView(R.id.noNetWokLayout)
    RelativeLayout noNetWokLayout;

    //视频控制器
    private MediaController mMediaController;

    //视频播放比例 16:9
    private int mDisplayAspectRatio = PLVideoTextureView.ASPECT_RATIO_16_9; //default

    private String mVideoPath;//视频播放地址
    private String mVideoName;//视屏播放名称
    private int mVideoHeight;//视频初始化高度
    private boolean isCanPlay = false;//是否 可以播放,此条件需要根据是否 wifi 环境来控制,默认 不可播放

    //视频当前播放位置
    private long curPosition = 0;
    //
//    //获取网络信息
    NetworkInfo info;
    private String videoIsChange;//视频是否转码中 转码中0  正常视频1;

    //目录实体类
    MenuDisplay currDisplayInfo;

    //课程详情 实体类
    CourseDetailsInfo courseDetailsInfo;

    //课程详情 dao
    CourseDao dao;

    //学习记录ID
    String studyId = "0";

    MenuDisplay nextMenuDisplay;//下一个素材

    String[] netWorkTip = {"网络未连接，请检查网络设置", "加载出错啦，请点击刷新重试"};

    /**
     * 实例化视频Fragment
     *
     * @return
     */
    public static VideoFragment newInstance(CourseDetailsInfo courseDetailsInfo, MenuDisplay currDisplayInfo, int videoHeight, MenuDisplay nextMenuDisplay) {
        VideoFragment videoFragment = new VideoFragment();

        Bundle args = new Bundle();
        args.putString("videoPath", currDisplayInfo.getFile());
        args.putString("videoName", currDisplayInfo.getNrmc());
        args.putInt("videoHeight", videoHeight);
        args.putString("videoIsChange", currDisplayInfo.getIschange());
        args.putSerializable("courseDetail", courseDetailsInfo);
        args.putSerializable("currDisplayInfo", currDisplayInfo);
        args.putSerializable("nextMenuDisplay", nextMenuDisplay);
        videoFragment.setArguments(args);
        return videoFragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        view = inflater.inflate(R.layout.course_video, null);
        ButterKnife.inject(this, view);

        //课程详情 dao
        dao = new CourseDao(this);

        //視頻播放地址
        if (getArguments() != null) {
            mVideoPath = getArguments().getString("videoPath");//获取视频地址
//            videoPath ="http://vod.sdust.edu.cn/files/2016-05/8vqql4hmxn28fa08.mp4"http://7xr954.com2.z0.glb.qiniucdn.com/20160513_57356bab99d3f387723585_0.mp4";//"http://devimages.apple.com/iphone/samples/bipbop/gear1/prog_index.m3u8";// "http://vod.sdust.edu.cn/files/2015-12//glf6awdaj9d18rcv.mp4";
            mVideoName = getArguments().getString("videoName");//获取视屏名称
            mVideoHeight = getArguments().getInt("videoHeight");//获取视频高度
            videoIsChange = getArguments().getString("videoIsChange");//视频是否转码中
            //获取课程详情
            courseDetailsInfo = (CourseDetailsInfo) getArguments().getSerializable("courseDetail");
            //获取当前目录信息
            this.currDisplayInfo = (MenuDisplay) getArguments().getSerializable("currDisplayInfo");
            //获取下一个素材
            nextMenuDisplay = (MenuDisplay) getArguments().getSerializable("nextMenuDisplay");
        }

        //判断视频是否转码中 转码中0
        if ("0".equals(videoIsChange)) {
            MessageUtils.showImageShortToast(getActivity(), "你查看的视频正在努力转换中，请稍候...");
            return view;
        }
        //配置视频信息
        optionVideo();

        videoNoWifiLayout.setVisibility(View.GONE);
        //设置视频布局高度
        mVideoView.getLayoutParams().height = mVideoHeight;
        //设置未播放视频时布局高度
//        videoNoWifiLayout.getLayoutParams().height = mVideoHeight;
        Log.d("视频默认高度：" + mVideoView.getHeight());

//        noNetWokLayout.getLayoutParams().height = mVideoHeight;

        //判断是否 wifi播放
        ConnectivityManager connectMgr = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
        //获取网络信息
        info = connectMgr.getActiveNetworkInfo();


        //判断过一次是否wifi 环境的情况了.就不用再判断该情况了,同一课程的视频都直接播放了
        if (CourseDetailActivity.isContinuePlay) {
            //设置视频地址
            setPlayVisible(true);
            playVideo();//播放视频

        } else {


            //wifi 环境是否可以播放 非 wifi 环境下提示框弹出
            if (info != null && info.getType() != ConnectivityManager.TYPE_WIFI) {
                //非 wifi 环境下不继续播放
                setPlayVisible(false);
                wifiDilog();
            }
            //wifi 环境正常 load
            else {
                //设置视频地址
                setPlayVisible(true);

                playVideo();
            }
        }


        return view;
    }


    /**
     * 视频配置信息
     */
    private void optionVideo() {
        //配置播放器信息
        AVOptions options = new AVOptions();

        // 准备超时时间，包括创建资源、建立连接、请求码流等，单位是 ms
        // 默认值是：无
//        options.setInteger(AVOptions.KEY_PREPARE_TIMEOUT, 120 * 1000);//准备时间 超时30秒
        // 读取视频流超时时间，单位是 ms
        // 默认值是：10 * 1000
//        options.setInteger(AVOptions.KEY_GET_AV_FRAME_TIMEOUT, 60 * 1000);
        // 当前播放的是否为在线直播，如果是，则底层会有一些播放优化
        // 默认值是：0
        options.setInteger(AVOptions.KEY_LIVE_STREAMING, 0);//点播0 直播1
        // 解码方式，codec＝1，硬解; codec=0, 软解
        // 默认值是：0
        options.setInteger(AVOptions.KEY_MEDIACODEC, 0);//软解 0 硬解1
        // 默认的缓存大小，单位是 ms
        // 默认值是：2000
        options.setInteger(AVOptions.KEY_CACHE_BUFFER_DURATION, 2000);

        // 最大的缓存大小，单位是 ms
        // 默认值是：4000
        options.setInteger(AVOptions.KEY_MAX_CACHE_BUFFER_DURATION, 4000);
        // 是否自动启动播放，如果设置为 1，则在调用 `prepareAsync` 或者 `setVideoPath` 之后自动启动播放，无需调用 `start()`
        // 默认值是：1
        options.setInteger(AVOptions.KEY_START_ON_PREPARED, 0);

        mVideoView.setAVOptions(options);//设置播放器配置信息

        //设置缓冲布局
        mVideoView.setBufferingIndicator(loadingView);
        //设置视频播放比例,默认16:9
        mVideoView.setDisplayAspectRatio(mDisplayAspectRatio);
        // 初始化播放控制器
        mMediaController = new MediaController(baseActivity, true, fcontainer, mVideoView, mVideoHeight, mVideoName);//配置控制器
        mMediaController.setVisibility(View.GONE);
        //设置控制器播放按钮监听
        mMediaController.setMediaPauseOrPlay(mediaPauseOrPlayListener);


        //视频播放保持手机高亮
//        mVideoView.setScreenOnWhilePlaying(true);
//      视频绑定控制器
        mVideoView.setMediaController(mMediaController);

        //设置播放完成监听
        mVideoView.setOnCompletionListener(mOnCompletionListener);
        //设置播放错误监听
        mVideoView.setOnErrorListener(mOnErrorListener);
        //是指定位置跳转完成监听
        mVideoView.setOnSeekCompleteListener(mOnSeekCompleteListener);
        mVideoView.setOnInfoListener(mOnInfoListener);
//        mVideoView.setOnPreparedListener(new PLMediaPlayer.OnPreparedListener() {
//            @Override
//            public void onPrepared(PLMediaPlayer plMediaPlayer) {
//                //  plMediaPlayer.seekTo(currDisplayInfo.getCurrent_time() * 1000);
//            }
//        });
    }

    /**
     * 播放视频
     */
    private void playVideo() {

        noNetWokLayout.setVisibility(View.GONE);
        loadingView.setVisibility(View.VISIBLE);
        //设置视频播放地址
        mVideoView.setVideoPath(mVideoPath);
        //播放视频
        mVideoView.start();

        //指定视频播放位置
        mVideoView.seekTo(currDisplayInfo.getCurrent_time() * 1000);


    }

    //是否 wifi
    @OnClick(R.id.video_noWifi)
    void playClick() {
        wifiDilog();
    }


    //是否无网络
    @OnClick(R.id.noNetWokLayout)
    void replayClick() {
        playVideo();
    }

    /**
     * 请求成功,请求成功
     */
    @Override
    public void onRequestSuccess(int requestCode) {
        try {
            if (dao.status.equals("0")) {
                switch (requestCode) {
                    //记录学习行为
                    case CodeConst.COURSE_SETBEHAVIOR_START:
                        studyId = dao.studyId;//记录学习行为ID
                        break;

                }
            } else {
                MessageUtils.showImageShortToast(getActivity(), dao.statusCode);
            }

        } catch (Exception e) {
//            Log.e(e.getMessage(), e);
//            MessageUtils.showImageShortToast(this, "请求数据异常");
        }
    }


    //是否 wifi 环境播放提示框
    public void wifiDilog() {
        new MaterialDialog.Builder(getActivity())
                .backgroundColor(Color.WHITE)
                .content("您正在使用非wifi网络，播放将产生流量费\n继续播放？")
                .contentColorRes(R.color.color_666)
                .positiveText("继续播放").positiveColorRes(R.color.colorAccent)
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        //设置视频地址
                        setPlayVisible(true);
//                        loadUrl(currDisplayInfo.getCurrent_time() * 1000);
                        playVideo();
                        isCanPlay = true;//视频可以在非 wifi 环境下播放
                        CourseDetailActivity.isContinuePlay = true;
                    }
                })
                .negativeText(R.string.disagree)
                .onNegative(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        isCanPlay = false;//不可以在非 wifi 环境下播放
                    }
                })
                .negativeColorRes(R.color.color_666)
                .cancelable(false)
                .show();
    }


    //设置视频播放可见
    private void setPlayVisible(boolean flag) {
        if (flag) {
            videoNoWifiLayout.setVisibility(View.GONE);
            fcontainer.setVisibility(View.VISIBLE);
        } else {
            videoNoWifiLayout.setVisibility(View.VISIBLE);
            fcontainer.setVisibility(View.GONE);
        }
    }

    @Override
    public void onResume() {
        super.onResume();


        mVideoView.start();
        //记录当前播放内容开始学习行为,并且不是课程老师,并且是已加入课程的
        if (courseDetailsInfo.getKcls() == 0) {
            dao.setBehavior(courseDetailsInfo.getKcid(), courseDetailsInfo.getCurrPmId(), courseDetailsInfo.getCurrMlId(), courseDetailsInfo.getCurrNrId(), "0", currDisplayInfo.getCurrent_time());
            Log.d("播放记录开始记录..." + courseDetailsInfo.getCurrNrId());
        }
    }

    @Override
    public void onPause() {
        super.onPause();


        mVideoView.pause();
        //并且不是课程老师 記錄當前播放時間
        if (courseDetailsInfo.getKcls() == 0) {

            curPosition = mVideoView.getCurrentPosition() / 1000;
            if (curPosition == 0) {
                curPosition = currDisplayInfo.getCurrent_time();
            }

            //结束学习记录记录学习行为
            if (!("0").equals(studyId)) {

                dao.setBehavior(courseDetailsInfo.getKcid(), courseDetailsInfo.getCurrPmId(), courseDetailsInfo.getCurrMlId(), courseDetailsInfo.getCurrNrId(), studyId, curPosition);
                Log.d("播放记录记录停止..." + courseDetailsInfo.getCurrNrId());
            }
        }
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        // 必须调用 要不直播有问题
        if (mVideoView != null) {
            //设置当前播放时间
            currDisplayInfo.setCurrent_time(curPosition - 10 < 0 ? 0 : (curPosition - 10));

            mVideoView.stopPlayback();
        }
        ButterKnife.reset(this);

    }


    /**
     * 控制器监听
     ********************************************/

    //设置播放,暂停按钮监听
    MediaController.MediaPauseOrPlayListener mediaPauseOrPlayListener = new MediaController.MediaPauseOrPlayListener() {
        @Override
        public void startVideo() {
//                MessageUtils.showShortToast(baseActivity,"开始播放");
            mVideoView.start();
        }

        @Override
        public void pauseVideo() {
//                MessageUtils.showShortToast(baseActivity,"暂停播放");
            mVideoView.pause();
        }
    };

    /**
     * 播放完成监听
     */
    private PLMediaPlayer.OnCompletionListener mOnCompletionListener = new PLMediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(PLMediaPlayer plMediaPlayer) {
//            MessageUtils.showShortToast(baseActivity,"Play Completed !");
            //平台收费
            if (Arad.preferences.getBoolean(LocalMark.IS_PAY.getName())) {
                //课程收费
                if (courseDetailsInfo.getIs_charge().equals("1")) {
                    if (courseDetailsInfo.getIsBuy() == 1) {
                        //购买成功
                        playNextSucai();
                    } else {
                        //暂停当前状态,
                        MessageUtils.showImageShortToast(getActivity(), "您查看的是收费课程，请先购买才能继续学习！");
                    }
                } else {
                    //课程不收费
                    playNextSucai();
                }
            } else {
                //平台不收费
                playNextSucai();
            }
        }
    };

    //播放下一个素材
    void playNextSucai() {
        //下一个素材不为空   视频播放完成跳转下一个素材;
        if (nextMenuDisplay != null) {
            Log.d("next==" + nextMenuDisplay.getNrid());
            baseActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//强制视频竖屏
            Log.d("nextMenu--=>" + nextMenuDisplay.getGpositon());
            Log.d("nextMenu-->"+nextMenuDisplay.getSpositon());
            Arad.bus.post(nextMenuDisplay);
        } else {
            Log.d("next=null");
        }
    }

    /**
     * 跳转到指定位置监听
     */
    private PLMediaPlayer.OnSeekCompleteListener mOnSeekCompleteListener = new PLMediaPlayer.OnSeekCompleteListener() {
        @Override
        public void onSeekComplete(PLMediaPlayer plMediaPlayer) {
//            MessageUtils.showShortToast(baseActivity,"onSeekComplete !");
            //调转到指定位置后自动播放
            plMediaPlayer.start();
        }

        ;
    };

    private PLMediaPlayer.OnInfoListener mOnInfoListener = new PLMediaPlayer.OnInfoListener() {
        @Override
        public boolean onInfo(PLMediaPlayer plMediaPlayer, int what, int extra) {
            Log.d("onInfo: " + what + ", " + extra);
            switch (what) {
                case PLMediaPlayer.MEDIA_INFO_BUFFERING_START:
                    //无网络提示消失

                    break;

                case PLMediaPlayer.MEDIA_INFO_BUFFERING_END:
                    loadingView.setVisibility(View.GONE);
                    break;

            }

            return false;
        }
    };
    /**
     * 视频播放错误监听
     */
    private PLMediaPlayer.OnErrorListener mOnErrorListener = new PLMediaPlayer.OnErrorListener() {
        @Override
        public boolean onError(PLMediaPlayer mp, int errorCode) {

            baseActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//强制视频竖屏


            long position = mp.getCurrentPosition();

            if (position != 0) {
                currDisplayInfo.setCurrent_time(position / 1000);
            }
            noNetWokLayout.setVisibility(View.VISIBLE);
            if (errorCode == PLMediaPlayer.ERROR_CODE_IO_ERROR) {

                noNetWorkTv.setText(netWorkTip[0]);

            } else {
                noNetWorkTv.setText(netWorkTip[1]);
            }

            switch (errorCode) {
                case PLMediaPlayer.ERROR_CODE_INVALID_URI:
//                    MessageUtils.showShortToast(baseActivity, "视频URL地址无效 !");
                    Log.d("视频URL地址无效");
                    break;
                case PLMediaPlayer.ERROR_CODE_404_NOT_FOUND:
//                    MessageUtils.showShortToast(baseActivity, "未发现播放资源404错误 !");
                    Log.d("未发现播放资源404错误");
                    break;
                case PLMediaPlayer.ERROR_CODE_CONNECTION_REFUSED:
                    MessageUtils.showShortToast(baseActivity, "服务器拒绝连接!");
                    Log.d("服务器拒绝连接");
                    break;
                case PLMediaPlayer.ERROR_CODE_CONNECTION_TIMEOUT:
//                    MessageUtils.showShortToast(baseActivity, "视频连接超时!");
                    Log.d("服务器拒绝连接");
                    break;
                case PLMediaPlayer.ERROR_CODE_EMPTY_PLAYLIST:
//                    MessageUtils.showShortToast(baseActivity, "未找到视频播放素材!");
                    Log.d("未找到视频播放素材");
                    break;
                case PLMediaPlayer.ERROR_CODE_STREAM_DISCONNECTED:
                    MessageUtils.showShortToast(baseActivity, "与服务器连接断开!");
                    Log.d("与服务器连接断开");
                    break;
                case PLMediaPlayer.ERROR_CODE_IO_ERROR:

//                    MessageUtils.showShortToast(baseActivity, "网络异常!");
                    Log.d("网络异常");
                    break;
                case PLMediaPlayer.ERROR_CODE_UNAUTHORIZED:
//                    MessageUtils.showShortToast(baseActivity, "未授权，播放一个禁播的流!");
                    Log.d("未授权，播放一个禁播的流");
                    break;
                case PLMediaPlayer.ERROR_CODE_PREPARE_TIMEOUT:
//                    MessageUtils.showShortToast(baseActivity, "播放器准备超时");
                    Log.d("播放器准备超时");
                    break;
                case PLMediaPlayer.ERROR_CODE_READ_FRAME_TIMEOUT:
//                    MessageUtils.showShortToast(baseActivity, "读取数据超时!");
                    Log.d("读取数据超时");
                    break;
                case PLMediaPlayer.MEDIA_ERROR_UNKNOWN:
                default:
//                    MessageUtils.showShortToast(baseActivity, "未知错误!");
                    Log.d("未知错误");
                    break;
            }
            // Todo pls handle the error status here, retry or call finish()
            mVideoView.stopPlayback();
//            finish();
//            playVideo();
            // If you want to retry, do like this:
//                mVideoView.setVideoPath(mVideoPath);
//                mVideoView.start();
//                //指定视频播放位置
//                mVideoView.seekTo(curPosition);
            // Return true means the error has been handled
            // If return false, then `onCompletion` will be called
            return true;
        }
    };

    /**
     * 屏幕方向改变时 (全屏)
     *
     * @param newConfig
     */
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        //正常 竖屏状态
        if (newConfig.orientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
            mMediaController.minScreen();//推出全屏
        }
        //横屏
        else {
            mMediaController.maxScreen();

        }


        super.onConfigurationChanged(newConfig);
    }


}
